package org.ws.task.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ws.task.model.HashKey;

import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public final class KeyUtils {

    private static Logger log = LoggerFactory.getLogger(KeyUtils.class.getName());

    private KeyUtils(){}

    public static String getNodeId(String workerName,String nodeId){
        return workerName+":"+nodeId;
    }

    public static String getTaskKey(Object o){
        if(o == null){
            return "0";
        }
        Class<?> clazz = o.getClass();
        Field field = findAnnFields(clazz,HashKey.class);
        if(field != null){
            try {
                PropertyDescriptor descriptor = new PropertyDescriptor(field.getName(),clazz);
                return String.valueOf(descriptor.getReadMethod().invoke(o));
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
        return o.toString();
    }

    private static Field findAnnFields(Class clazz, Class<? extends Annotation> annClass){
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            Annotation annotation = field.getAnnotation(annClass);
            if(annotation != null){
                return field;
            }
        }
        // 当前类获取不到，逐级从父类获取
        Class superclass = clazz.getSuperclass();
        if(superclass != null){
            return findAnnFields(superclass,annClass);
        }
        return null;
    }
}
